package cn.bytest.netty.exchange;

import cn.bytets.rpc.api.Channel;
import cn.bytets.rpc.api.RpcClient;
import cn.bytets.rpc.api.exchange.DefaultFuture;
import cn.bytets.rpc.api.exchange.ExchangeClient;
import cn.bytets.rpc.api.message.Request;
import cn.bytets.rpc.common.URL;

import java.util.concurrent.CompletableFuture;

public class NettyExchangeClient implements ExchangeClient {

    private RpcClient client;

    public NettyExchangeClient(RpcClient client){
        this.client = client;
    }

    @Override
    public CompletableFuture<Object> request(Object message, URL url) {
        return request(message, 3000,url);
    }

    @Override
    public CompletableFuture<Object> request(Object message, int timeout,URL url) {
        Request request = new Request(message);
        Channel channel = client.getChannel(url);
        channel.setRequest(request);
        DefaultFuture defaultFuture = DefaultFuture.newFuture(channel, request, timeout);
        try {
            channel.send(request);
        } catch (Exception e) {
            defaultFuture.cancel();
            throw e;
        }
        return defaultFuture;
    }

    @Override
    public void reconnect(URL url) {
        client.connect(url.getHost(),url.getPort());
    }
}
